{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Top and Bottom Performing\n",
    "Let's look at how we might get the top performing stocks for a single period. For this example, we'll look at just a single month of closing prices:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "month = pd.to_datetime('02/01/2018')\n",
    "close_month = pd.DataFrame(\n",
    "    {\n",
    "        'A': 1,\n",
    "        'B': 12,\n",
    "        'C': 35,\n",
    "        'D': 3,\n",
    "        'E': 79,\n",
    "        'F': 2,\n",
    "        'G': 15,\n",
    "        'H': 59},\n",
    "    [month])\n",
    "\n",
    "close_month"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`close_month` gives use the prices for the month of February, 2018 for all the stocks in this universe (A, B, C, ...). Looking at these prices, we can see that the top 2 performing stocks for that month was E and H with the prices 79 and 59.\n",
    "\n",
    "To get this using code, we can use the [`Series.nlargest`](https://pandas.pydata.org/pandas-docs/version/0.21/generated/pandas.Series.nlargest.html) function. This function returns the items with the *n* largest numbers. For the example we just talked about, our *n* is 2."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "try:\n",
    "    # Attempt to run nlargest\n",
    "    close_month.nlargest(2)\n",
    "except TypeError as err:\n",
    "    print('Error: {}'.format(err))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "What happeened here? It turns out we're not calling the [`Series.nlargest`](https://pandas.pydata.org/pandas-docs/version/0.21/generated/pandas.Series.nlargest.html) function, we're actually calling [`DataFrame.nlargest`](https://pandas.pydata.org/pandas-docs/version/0.21/generated/pandas.DataFrame.nlargest.html), since `close_month` is a DataFrame. Let's get the Series from the dataframe using `.loc[month]`, where `month` is the 2018-02-01 index created above."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "close_month.loc[month].nlargest(2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Perfect! That gives us the top performing tickers for that month. Now, how do we get the bottom performing tickers? There's two ways to do this. You can use Panda's [`Series.nsmallest`](https://pandas.pydata.org/pandas-docs/version/0.21/generated/pandas.Series.nsmallest.html) function or just flip the sign on the prices and then apply [`DataFrame.nlargest`](https://pandas.pydata.org/pandas-docs/version/0.21/generated/pandas.DataFrame.nlargest.html). Either way is fine. For this course, we'll flip the sign with nlargest. This allows us to reuse any funtion created with nlargest to get the smallest.\n",
    "\n",
    "To get the bottom 2 performing tickers from `close_month`, we'll flip the sign."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "(-1 * close_month).loc[month].nlargest(2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "That gives us the bottom performing tickers, but not the actual prices. To get this, we can flip the sign from the output of nlargest."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "(-1 * close_month).loc[month].nlargest(2) *-1"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now you've seen how to get the top and bottom performing prices in a single month. Let's see if you can apply this knowledge.\n",
    "## Quiz\n",
    "Implement `date_top_industries` to find the top performing closing prices and return their sectors for a single date. The function should only return the [set](https://docs.python.org/3/tutorial/datastructures.html#sets) of sectors, there shouldn't be any duplicates returned.\n",
    "\n",
    "- The number of top performing prices to look at is represented by the parameter `top_n`.\n",
    "- The `date` parameter is the date to look for the top performing prices in the `prices` DataFrame.\n",
    "- The sector information for each ticker is located in the `sector` parameter.\n",
    "\n",
    "For example:\n",
    "```\n",
    "                 Prices\n",
    "               A         B         C         D         E\n",
    "2013-07-08     2         2         7         2         6\n",
    "2013-07-09     5         3         6         7         5\n",
    "...            ...       ...       ...\n",
    "\n",
    "           Sector\n",
    "A       \"Utilities\"       \n",
    "B       \"Health Care\"       \n",
    "C       \"Real Estate\"\n",
    "D       \"Real Estate\"\n",
    "E       \"Information Technology\"\n",
    "\n",
    "Date:  2013-07-09\n",
    "Top N: 3\n",
    "```\n",
    "The set created from the function `date_top_industries` should be the following:\n",
    "```\n",
    "{\"Utilities\", \"Real Estate\"}\n",
    "```\n",
    "*Note: Stock A and E have the same price for the date, but only A's sector got returned. We'll keep it simple and only take the first occurrences of ties.*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import project_tests\n",
    "\n",
    "\n",
    "def date_top_industries(prices, sector, date, top_n):\n",
    "    \"\"\"\n",
    "    Get the set of the top industries for the date\n",
    "    \n",
    "    Parameters\n",
    "    ----------\n",
    "    prices : DataFrame\n",
    "        Prices for each ticker and date\n",
    "    sector : Series\n",
    "        Sector name for each ticker\n",
    "    date : Date\n",
    "        Date to get the top performers\n",
    "    top_n : int\n",
    "        Number of top performers to get\n",
    "    \n",
    "    Returns\n",
    "    -------\n",
    "    top_industries : set\n",
    "        Top industries for the date\n",
    "    \"\"\"\n",
    "    # TODO: Implement Function\n",
    "    \n",
    "    return None\n",
    "\n",
    "\n",
    "project_tests.test_date_top_industries(date_top_industries)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Quiz Solution\n",
    "If you're having trouble, you can check out the quiz solution [here](top_and_bottom_performing_solution.ipynb)."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
